import { is } from '@electron-toolkit/utils'
import { BrowserWindow, ipcMain, IpcMainInvokeEvent } from 'electron'
import { join } from 'path'
const iconv = require('iconv-lite')
const axios = require('axios')
let settingsWindow: BrowserWindow | null = null
//创建新窗口
function createSettingWindow(): void {
  settingsWindow = new BrowserWindow({
    width: 800,
    frame: false,
    transparent: true,
    autoHideMenuBar: true,
    height: 600,
    webPreferences: {
      preload: join(__dirname, '../preload/index.js'),
      sandbox: false
    }
  })
  if (is.dev && process.env['ELECTRON_RENDERER_URL']) {
    settingsWindow.loadURL(process.env['ELECTRON_RENDERER_URL'] + '#/setting')
  } else {
    settingsWindow.loadFile(join(__dirname, '../renderer/index.html'), { hash: '#/setting' })
  }

  settingsWindow.on('closed', () => {
    // 清理新窗口的引用
    settingsWindow = null
  })
}

ipcMain.handle('baidu', async (_: IpcMainInvokeEvent, query: string = '') => {
  let url = `https://suggestion.baidu.com/su?wd=${query}`
  let res = await axios.get(url, { responseType: 'arraybuffer' })
  let gbkData = iconv.decode(res.data, 'gbk')
  return gbkData
})

ipcMain.on('create-setting-window', () => {
  //已有设置窗口则不打开
  if (!settingsWindow) {
    createSettingWindow()
  }
})
ipcMain.on('close-settings-window', () => {
  if (settingsWindow) {
    settingsWindow.close()
  }
})
